<template>
  <div>
    <MyTable :list="list">
      <template #header>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="{ row }">
        <td>{{row.id}}</td>
        <td>{{row.goods_name}}</td>
        <td>{{row.goods_price}}</td>
        <td>
          <!-- input输入框 -->
          <input
            class="tag-input form-control"
            style="width: 100px"
            type="text"
            v-if="row.inputVisible"
            v-fff
            v-model="row.inputValue"
            @keydown.enter="addTag(row)"
            @keydown.esc="row.inputValue = ''"
            @blur="row.inputVisible = false"
          />
          <!-- Tags按钮 -->
          <button
            v-else
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            @click="row.inputVisible = true"
          >
            +Tag
          </button>
          <!-- 标签显示 -->
          <span
            v-for="(str, ind) in row.tags"
            :key="ind"
            class="badge badge-warning"
          >
            {{ str }}
          </span>
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="delBtn(row.id)">删除</button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from '../components/MyTable'

export default {
  components: {
    MyTable,
  },
  data() {
    return {
      list: [], // 所有数据
    }
  },
  methods: {
    addTag(obj) {
      if(obj.inputValue.trim() === '') {
        return alert('输入不能为空')
      }
      obj.tags.push(obj.inputValue)
      obj.inputValue = ""
    },
    delBtn(id) {
      this.list = this.list.filter(item => item.id !== id)
    }
  },
  created() {
    this.$axios({
      url: '/api/goods',
    })
      .then((res) => {
        console.log(res)
        this.list = res.data.data
      })
      .catch((err) => {
        console.log(err)
      })
  },
  directives: {
    fff: {
      inserted(el) {
        el.focus()
      }
    }
  }
}
</script>

<style scoped>
.badge-warning {
  margin-right: 5px;
}
</style>